import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/manage/adjust/adjustmodel.dart';
import 'package:opene/ui/manage/managedialogscreen.dart';
import 'package:toast/toast.dart';

class CCLocationTrkScreen extends StatelessWidget {
  CycleCountBean cycleCountBean;

  CCLocationTrkScreen({this.cycleCountBean});

  @override
  Widget build(BuildContext context) {
    return CCLocationTrkScreenPage(cycleCountBean: cycleCountBean);
  }
}

class CCLocationTrkScreenPage extends StatefulWidget {
  CycleCountBean cycleCountBean;

  CCLocationTrkScreenPage({this.cycleCountBean});

  @override
  _CCLocationTrkPageState createState() => _CCLocationTrkPageState(cycleCountBean: cycleCountBean);
}

class _CCLocationTrkPageState extends BaseState<CCLocationTrkScreen> {
  CycleCountBean cycleCountBean;
  String trkList = "Trackings List(0)";
  List<ReturnCycleListDTO> data = new List();

  _CCLocationTrkPageState({this.cycleCountBean});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "CycleCount: Scan TRK#";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    "Location: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "IBLPN: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      Utils.getStringisEmpty(cycleCountBean.location),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      Utils.getStringisEmpty(cycleCountBean.lpn),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 35),
            child: TextField(
              controller: textEditingController,
              textInputAction: TextInputAction.search,
              onSubmitted: (String text) {
                print('Searching for $text');
                if (Utils.isEmpty(text)) {
                  return;
                }
                getLpnPhotoInfo(text);
              },
              // autofocus: true,
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  padding: EdgeInsets.all(2.0),
                  icon: Icon(
                    Icons.qr_code_scanner,
                    size: 28,
                    color: MyAppTheme.nearlyBlue,
                  ),
                  onPressed: () {
                    // requestPermissions();
                    // Utils.scanBarcode(context);
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return ScanCode();
                    })).then((text) {
                      if (text == null) {
                        return;
                      }
                      setState(() {
                        textEditingController.text = text;
                      });
                      print(text); //拿到扫描结果
                      getLpnPhotoInfo(text);
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: MyAppTheme.nearlyBlue,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点之外的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点时的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                hintText: "scan trk#",
                filled: true,
                fillColor: MyAppTheme.white,
                //隐藏下划线
                //border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
              ),
              onChanged: (text) {
                code = text;
              },
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Text(
            "Please scan the barcode of the returned waybill TRK#！",
            style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                child: Text(
                  data == null ? "TRK#(--)" : "TRK#(${Utils.getStringisInteger(data.length)})",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
              Expanded(
                child: Text(
                  "SKU",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(child: setListView())
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        ReturnCycleListDTO trk = data[index];
        return Column(
          children: [
            Visibility(
                visible: index == 0 ? true : false,
                child: SizedBox(
                  height: 5,
                )),
            Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: Text(
                    Utils.getStringisEmpty(trk.trackingCode),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: Row(
                    children: [
                      Expanded(
                        flex: 2, //设置权重
                        child: Text(
                          Utils.getStringisEmpty(trk.sku),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        ),
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      GestureDetector(
                        onTap: () {
                          if (data.length <= index) {
                            return;
                          }
                          setState(() {
                            data.removeAt(index);
                          });
                        },
                        child: Icon(
                          Icons.delete,
                          size: 20,
                          color: MyAppTheme.red,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void getLpnPhotoInfo(String trackingCode) async {
    updateHint('');
    CycleCountLocationLpnQr countSkuQr = CycleCountLocationLpnQr();
    countSkuQr.lpn = cycleCountBean.lpn;
    countSkuQr.trackingCode = trackingCode;
    String json = jsonEncode(countSkuQr);

    // 显示加载中对话框
    LoadingIndicator.show(context, title: "Submit...");

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnCycleCountScanTrk, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      ReturnCycleListDTO returnCycleListDTO = ReturnCycleListDTO.fromJson(baseResponse.data);
      if (returnCycleListDTO == null) {
        return;
      }
      if (data != null) {
        for (ReturnCycleListDTO returnCycle in data) {
          if (returnCycle.shortTrackingCode == returnCycleListDTO.shortTrackingCode) {
            return;
          }
        }
      }
      if (data == null) {
        data = new List();
      }
      setState(() {
        data.add(returnCycleListDTO);
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void returnCycleCountSkuSubmit(CCSkuTrk ccSkuTrk) async {
    updateHint('');

    String json = jsonEncode(ccSkuTrk);
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnCycleCount, method: BaseMethod.post, data: json);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      CycleCountBean cycleCountSku2 = CycleCountBean.fromJson(baseResponse.data);
      cycleCountSku2.location = cycleCountBean.location;
      Navigator.of(context).pop(cycleCountSku2);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  int num;

  @override
  void setNext() {
    CCSkuTrk ccSkuTrk = new CCSkuTrk();
    ccSkuTrk.location = cycleCountBean.location;
    ccSkuTrk.lpn = cycleCountBean.lpn;
    if (data == null || data.length == 0) {
      num = 0;
      if (cycleCountBean.latest_inventory != null) {
        for (InventoryListDTO inventoryDTO in cycleCountBean.latest_inventory) {
          num = num + Utils.getIntegerisEmpty(inventoryDTO.quantity);
        }
      }
      showDialog(
        context: context,
        builder: (context) => CCSkuTrkDialog(
          inventory: num,
          qty: 0,
        ),
      ).then((value) => {
            print("result2:${value}"),
            if ((value != null) && (value == "ok")) {returnCycleCountSkuSubmit(ccSkuTrk)}
          });
      return;
    }
    ccSkuTrk.returnCycleList = data;
    returnCycleCountSkuSubmit(ccSkuTrk);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
